package com.gko100.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

import org.aspectj.util.FileUtil;
import org.json.simple.JSONObject;

import com.gko100.action.base.AdminBaseAction;
import com.gko100.model.Image;
import com.opensymphony.xwork2.ActionContext;

public class KindAction extends AdminBaseAction {
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	private File imgFile;
    /**
     * 文件名称
     */
    private String imgFileFileName;

    /**
     * 图片宽度
     */
    private String imgWidth;

    /**
     * 图片高度
     */
    private String imgHeight;

    /**
     * 图片对齐方式
     */
    private String align;

    /**
     * 图片标题
     */
    private String imgTitle;
    
    private String savePath;
    

	public String getSavePath() {
		return savePath;
	}
	
  
    public File getImgFile() {
		return imgFile;
	}


	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}


	public String getImgFileFileName() {
		return imgFileFileName;
	}


	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}


	public String getImgWidth() {
		return imgWidth;
	}


	public void setImgWidth(String imgWidth) {
		this.imgWidth = imgWidth;
	}


	public String getImgHeight() {
		return imgHeight;
	}


	public void setImgHeight(String imgHeight) {
		this.imgHeight = imgHeight;
	}


	public String getAlign() {
		return align;
	}


	public void setAlign(String align) {
		this.align = align;
	}


	public String getImgTitle() {
		return imgTitle;
	}


	public void setImgTitle(String imgTitle) {
		this.imgTitle = imgTitle;
	}


	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}


				/** 
     * 上传图片 
     * @return 
     */  
    public String uploadImage() throws Exception {
    	
    	request = ServletActionContext.getRequest();
    	response = ServletActionContext.getResponse();
        response.setContentType("text\\html; charset=UTF-8");
        ActionContext ctx = ActionContext.getContext();
        // 文件保存目录路径
        savePath=ServletActionContext.getServletContext().getRealPath("\\upload") + "\\"+ctx.getSession().get("nav").toString()+"\\";
        System.out.println("savePath============"+savePath);
        // 文件保存目录URL
        String saveUrl = "http://" +request.getServerName() + ":"+request.getServerPort() + request.getContextPath()+"/upload/"+ctx.getSession().get("nav").toString()+"/";
        System.out.println("saveUrl============"+saveUrl);
        // 定义允许上传的文件扩展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
        // 最大文件大小
        long maxSize = 2000000;
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (imgFile == null) {
            out.println(getError("请选择文件。"));
            return null;
        }

        // 检查目录
        File uploadDir = new File(this.getSavePath());
        System.out.println("uploadDir=============="+uploadDir);
        if (!uploadDir.isDirectory()) {
        	uploadDir.mkdirs();
            
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            out.println(getError("上传目录没有写权限。"));
            return null;
        }
        // 创建文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "\\";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
		String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
            out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
            return null;
        }
        if (imgFile.length() > maxSize) {
            out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制，文件大小[ " + imgFile.length() + " ]，限制为[ " + maxSize + " ] "));
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        
      
        try {
            FileUtil.copyFile(imgFile, uploadedFile);
            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", saveUrl + newFileName);
            
            out.println(obj.toString());
           
        } catch (IOException e) {
            e.printStackTrace();
        }

        Image image=new Image();
        image.setImgSaveName(newFileName);
        image.setImgSrcName("upload/"+ctx.getSession().get("nav").toString()+"/"+ymd+"/");
        image.setImgUrl(saveUrl+newFileName);
        List<Image> imageList = (List<Image>) ctx.getSession().get("imageList");
        imageList.add(image);
        
        ctx.getSession().put("imageList", imageList);
        return null;
    }
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        return obj.toString();
    }


}
